#include "UdpClient.hpp"
#include "Common.hpp"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <signal.h>


int sockfd = -1;
struct sockaddr_in server;

void ClinetQuit(int sig)
{
    (void)sig;
    std::string quit = "QUIT";
    int n = ::sendto(sockfd, quit.c_str(), quit.size(), 0, CONV(&server), sizeof(server));
    exit(0);
}

void *Recver(void *args)
{
    while (true)
    {
        (void)args;
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl; // cerr
            // fprintf(stdout,"%s",buffer);
        }
    }
}
// CS模式：客户主动发起访问
// ./client_udp serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        exit(USAGE_ERR);
    }

    signal(2,ClinetQuit);

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    // 1. 创建socket
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    // 1.1填充server信息
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    // 2.2 接受服务器消息
    // 创建给线程接受消息
    pthread_t tid;
    pthread_create(&tid, nullptr, Recver, nullptr);

    // 1.2启动的时候，给服务器推送消息
    std::string online = "....来了哈！";
    int n = ::sendto(sockfd, online.c_str(), online.size(), 0, CONV(&server), sizeof(server));


    // 2. clientdone
    while (true)
    {
        // 2.1 给服务器发消息
        usleep(1000);
        printf("Please Enter# ");
        std::string message;
        std::getline(std::cin, message);
        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
    }
    return 0;
}